"""
RedFire Notification Service - Refactored
"""
import sys
from pathlib import Path
import logging.config

# ----------------- PATH SETUP -----------------
# Ensure the shared module can be found
try:
    current_file = Path(__file__).resolve()
    project_root = current_file.parents[4]
    if str(project_root) not in sys.path:
        sys.path.insert(0, str(project_root))
except IndexError:
    project_root = Path.cwd()
    # Adjust path if needed for different execution contexts
    if "shared" not in [p.name for p in project_root.iterdir()]:
        while "shared" not in [p.name for p in project_root.iterdir()] and project_root != project_root.parent:
            project_root = project_root.parent
    if str(project_root) not in sys.path:
         sys.path.insert(0, str(project_root))

from fastapi import FastAPI
from sqlalchemy.ext.asyncio import AsyncSession
from redis.asyncio import Redis

from redfire_framework import RedFireContainer, RedFireSettings
from redfire_framework.core.database import DatabaseManager as UnifiedDatabaseManager
from redfire_framework.cache.backends import RedisCache as RedisManager
from redfire_framework.logging.manager import configure_logging as get_log_config

from .services.notification_service import NotificationService
from .api import notification_routes
from .core import exceptions # Assuming exceptions are defined here

# ----------------- GLOBAL SINGLETONS -----------------
db_manager: UnifiedDatabaseManager = None
redis_manager: RedisManager = None
notification_service: NotificationService = None
service_config = ConfigManager().get_service_config("notification-service")

# ----------------- DEPENDENCY INJECTION PROVIDERS -----------------
async def get_db_session() -> AsyncSession:
    """Provides a database session for a single request."""
    if not db_manager:
        raise RuntimeError("DatabaseManager not initialized.")
    async with db_manager.get_session() as session:
        yield session

async def get_redis_client() -> Redis:
    """Provides a Redis client for a single request."""
    if not redis_manager:
        raise RuntimeError("RedisManager not initialized.")
    return redis_manager.get_client()

def get_notification_service() -> NotificationService:
    """Provides the singleton instance of the NotificationService."""
    if not notification_service:
        raise RuntimeError("NotificationService not initialized.")
    return notification_service

# ----------------- SERVICE LIFECYCLE -----------------
class NotificationServiceApp(ServiceBase):
    """Encapsulates the Notification Service FastAPI application."""

    def __init__(self):
        super().__init__(service_name="notification-service", config=service_config)

    async def on_startup(self):
        """Initializes all necessary resources and managers on service startup."""
        global db_manager, redis_manager, notification_service
        
        self.logger.info("Notification Service starting up...")
        
        # 1. Initialize Database Manager using centralized database configuration system
        try:
            from shared.data.db_config import load_all_databases, register_all_databases
            
            # Load standardized database configuration
            db_config = load_all_databases("notification-service", service_config)
            self.logger.info(f"✅ Loaded {len(db_config.databases)} database configuration(s)")
            
            # Register all databases to the manager
            db_manager = await register_all_databases("notification-service", db_config)
            self.logger.info("✅ Database connection established via centralized config system")
        except Exception as e:
            self.logger.error(f"❌ New database config system failed: {e}")
            
            # Fallback to legacy configuration method
            try:
                self.logger.warning("🔄 Falling back to legacy database configuration")
                legacy_db_config = service_config.get('database', {}).get('postgres_notifications', {})
                if not legacy_db_config:
                    raise ValueError("PostgreSQL notifications database config not found in legacy format")
                
                db_manager = UnifiedDatabaseManager(config=legacy_db_config, engine_type='postgres')
                await db_manager.initialize()
                self.logger.info("✅ Database connection established via legacy fallback")
            except Exception as fallback_error:
                self.logger.critical(f"❌ Database initialization failed completely: {fallback_error}", exc_info=True)
                raise

        # 2. Initialize Redis Manager
        redis_config = service_config.get('redis', {})
        redis_manager = RedisManager(config=redis_config)
        await redis_manager.initialize()
        self.logger.info("RedisManager initialized successfully.")

        # 3. Initialize the Notification Service (now stateless)
        notification_service = NotificationService(
            db_manager=db_manager,
            redis_manager=redis_manager,
            config=service_config.get('notifications', {})
        )
        self.logger.info("NotificationService singleton created.")

        await super().on_startup()

    async def on_shutdown(self):
        """Cleans up resources on service shutdown."""
        self.logger.info("Notification Service shutting down...")
        if db_manager:
            await db_manager.close()
            self.logger.info("Database connections closed.")
        if redis_manager:
            await redis_manager.close()
            self.logger.info("Redis connections closed.")
        await super().on_shutdown()

    def create_app(self) -> FastAPI:
        """Creates and configures the FastAPI application instance."""
        log_config = get_log_config(self.service_name, self.config.get('logging', {}))
        logging.config.dictConfig(log_config)

        app = super().create_app()
        
        # Include API routes
        app.include_router(notification_routes.router, prefix="/api/v1")
        self.logger.info("Notification API routes registered under /api/v1/notifications.")
        
        return app

# ----------------- APPLICATION FACTORY -----------------
def create_service() -> ServiceBase:
    """Factory function to create the service instance."""
    return NotificationServiceApp()

# Entry point for running the service directly
if __name__ == "__main__":
    service_app = create_service()
    service_app.run()